Constraint = 
{
	Properties=
	{
		radius = 0.03,
		damping = 0,
		bNoSelfCollisions = 1,
		bUseEntityFrame=1,
		max_pull_force=0,
		max_bend_torque=0,
		Limits = {
		  x_min = 0,
		  x_max = 0,
		  yz_min = 0,
		  yz_max = 0,
		}
	},
	bWasDetached = 0,
	idEnt,
	idConstr = -1,

	Editor=
	{
		Icon="Magnet.bmp",
		ShowBounds = 1,
	},
}

function Constraint:OnReset()
	self.idEnt = nil;
end

function Constraint:Apply()
	local ConstraintParams = {pivot={},frame0={},frame1={}};
	if self.idEnt then
	
	else
		local ents = Physics.SamplePhysEnvironment(self:GetPos(), self.Properties.radius);
		if (ents[1] and ents[6]) then  
			CopyVector(ConstraintParams.pivot, self:GetPos());
			if self.Properties.bUseEntityFrame==1 then
				CopyVector(ConstraintParams.frame1, ents[1]:GetAngles());
			else
				CopyVector(ConstraintParams.frame1, self:GetAngles());
			end	
			CopyVector(ConstraintParams.frame0, ConstraintParams.frame1);
			ConstraintParams.entity_part_id_1 = ents[2];
			ConstraintParams.phys_entity_id = ents[6];
			ConstraintParams.entity_part_id_2 = ents[5];
			ConstraintParams.xmin = self.Properties.Limits.x_min;
			ConstraintParams.xmax = self.Properties.Limits.x_max;
			ConstraintParams.yzmin = self.Properties.Limits.yz_min;
			ConstraintParams.yzmax = self.Properties.Limits.yz_max;
			ConstraintParams.ignore_buddy = self.Properties.bNoSelfCollisions;
			ConstraintParams.damping = self.Properties.damping;
			ConstraintParams.sensor_size = self.Properties.radius;
			ConstraintParams.max_pull_force = self.Properties.max_pull_force;
			ConstraintParams.max_bend_torque = self.Properties.max_bend_torque;
			idConstr = ents[1]:SetPhysicParams(PHYSICPARAM_CONSTRAINT, ConstraintParams);
			idEnt = ents[1].id;
		end		
	end
end

function Constraint:OnStartGame()
	self:Apply();
end

function Constraint:OnPropertyChange()
	self:OnReset();
end

function Constraint:OnInit()
	self:OnReset();
end

function Constraint:Event_ConstraintBroken(sender)
	BroadcastEvent( self,"ConstraintBroken");
end

function Constraint:OnSave( props )
	props.idEnt = self.idEnt;
	props.idConstr = self.idConstr;
	props.bWasDetached = self.bWasDetached;
end

function Constraint:OnLoad( props )
	self.idEnd = props.idEnt;
	self.idConstr = props.idConstr;
	self.bWasDetached = props.bWasDetached;
end 

function Constraint:OnShutDown()
end

Constraint.FlowEvents =
{
	Inputs =
	{
		ConstraintBroken = { Constraint.Event_ConstraintBroken, "bool" },
	},
	Outputs =
	{
		ConstraintBroken = "bool",
	},
}